<?php

namespace app\redis;

use Yii;

/**
 * Class Cache
 * @package app\redis
 */
class Cache
{
    use Key;

    /**
     * redis instance
     *
     * @return yii\redis\Connection | null
     */
    protected static function getRedis()
    {
        $redis = Yii::$app->redis;
        if ($redis) {
            return $redis;
        }

        return null;
    }

    public static function get($key)
    {
        $redis = self::getRedis();
        if ($redis) {
            return $redis->get($key);
        }

        return null;
    }

    public static function set($key, $data, $expire = -1)
    {
        $redis = self::getRedis();
        if ($redis) {
            if ($expire === -1) {
                $config = require __DIR__ . '/../controllers/config.php';
                $cache = $config['cache'];
                $expire = $cache + mt_rand(1, 3600 * 5);
            }
            $redis->setex($key, $expire, $data);
        }
    }

    public static function delete($key)
    {
        $redis = self::getRedis();
        if ($redis) {
            return $redis->del($key);
        }

        return false;
    }

    public static function keys($key)
    {
        $redis = self::getRedis();
        if ($redis) {
            return $redis->keys($key . '*');
        }

        return [];
    }

    public static function deleteAll($key) {
        $keys = self::keys($key);
        if ($keys) {
            foreach ($keys as $k) {
                self::delete($k);
            }
        }
    }

    public static function flushAll()
    {
        $redis = self::getRedis();
        if ($redis) {
            return $redis->flushall();
        }

        return true;
    }
}